package cn.itcast.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
import com.github.pagehelper.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符集编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取页面参数
        String method = req.getParameter("method");
        System.out.println(method);
        if ("login".equals(method)){
            login(req,resp);
        }else  if ("findAll".equals(method)){
            findAll(req,resp);
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //调用service方法查询用户
        User user = userService.findById(username, password);

        if (user!= null){//登录成功


            req.getRequestDispatcher("user?method=findAll").forward(req,resp);
        }else{
            resp.getWriter().write("登录失败");
        }


    }

    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取当前页是第几页
        String pageN = req.getParameter("pageNum");
        Integer pageNum = null;
        if (pageN != null && !"".equals(pageN)){
             pageNum = Integer.parseInt(pageN);
        }
        if (pageNum == null){
            pageNum = 1;
        }
        //调用service方法查询所有用户
        List<User> list = userService.findAll(pageNum);
        //获取分页数据
        PageInfo<User> pageInfo = new PageInfo<>(list);

        req.setAttribute("pageInfo",pageInfo);

        req.getRequestDispatcher("/main.jsp").forward(req,resp);

    }
}
